import React, { useState, useEffect, useRef } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, ScrollView, Modal, NativeSyntheticEvent, TextInputKeyPressEventData, Platform, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/AntDesign';

// 设计稿尺寸
const DESIGN_WIDTH = 375;
const DESIGN_HEIGHT = 812;

// 工具函数：按照设计稿尺寸计算实际尺寸
const { width: screenWidth, height: screenHeight } = Platform.OS === 'web' 
  ? { width: 375, height: 812 } 
  : require('react-native').Dimensions.get('window');

// 宽度比例换算
const wp = (size: number) => {
  return (screenWidth / DESIGN_WIDTH) * size;
};

// 高度比例换算
const hp = (size: number) => {
  return (screenHeight / DESIGN_HEIGHT) * size;
};

// 字体大小换算
const sp = (size: number) => {
  const scale = Math.min(screenWidth / DESIGN_WIDTH, screenHeight / DESIGN_HEIGHT);
  return size * scale;
};

// 定义 RootStackParamList 类型
type RootStackParamList = {
    // 这里可以根据你的实际页面参数进行定义
    // 示例：如果有一个页面叫 Home，无参数
    Home: undefined;
    // 假设 Ke 页面也无参数
    Ke: undefined;
};

type NavigationProp = StackNavigationProp<RootStackParamList>;

// 定义消息类型
interface Message {
    type: string;
    fromUserId?: string;
    fromUserType?: string;
    message: string;
    timestamp: string;
    isLocal?: boolean;
}

// 定义WebSocket消息类型
interface WebSocketMessage {
    type: string;
    userId?: string;
    userType?: string;
    messages?: Message[];
    message?: string;
    fromUserId?: string; // 添加缺失的属性
}

const Ke: React.FC = () => {
    const navigation = useNavigation<NavigationProp>();
    const [messages, setMessages] = useState<Message[]>([
        {
            type: 'message',
            fromUserId: 'doctor',
            fromUserType: 'service',
            message: '您好！我是张医生，很高兴为您服务。\n请问有什么可以帮您?',
            timestamp: new Date().toISOString()
        },
        {
            type: 'message',
            fromUserId: 'user',
            fromUserType: 'customer',
            message: '医生您好，我最近总感觉头晕，该怎么办？',
            timestamp: new Date().toISOString()
        }
    ]);
    const [inputValue, setInputValue] = useState<string>('');
    const [userId, setUserId] = useState<string | null>(null);
    const [userType, setUserType] = useState<'customer' | 'service'>('customer');
    const [connected, setConnected] = useState<boolean>(false);
    const [showSettings, setShowSettings] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [connecting, setConnecting] = useState<boolean>(false);
    const [showClearConfirm, setShowClearConfirm] = useState<boolean>(false);

    const wsRef = useRef<WebSocket | null>(null);
    const chatAreaRef = useRef<ScrollView>(null);
    const messageEndRef = useRef<View>(null);
    const reconnectTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
    const prevMessagesLengthRef = useRef<number>(0);

    // 聊天区域自动滚动到底部
    useEffect(() => {
        if (messages.length > prevMessagesLengthRef.current && chatAreaRef.current) {
            chatAreaRef.current.scrollToEnd({ animated: true });
            prevMessagesLengthRef.current = messages.length;
        }
    }, [messages]);

    // 建立WebSocket连接
    useEffect(() => {
        if (reconnectTimeoutRef.current) {
            clearTimeout(reconnectTimeoutRef.current);
        }

        const connectWebSocket = () => {
            try {
                console.log('尝试连接WebSocket...');
                setConnecting(true);
                const ws = new WebSocket('ws://172.20.10.2:8088'); // 使用更稳定的域名代替IP
                wsRef.current = ws;

                ws.onopen = () => {
                    console.log('WebSocket连接已建立');
                    setConnected(true);
                    setConnecting(false);
                    setError(null);

                    if (userType !== 'customer' && ws.readyState === 1) {
                        console.log('发送用户类型设置:', userType);
                        ws.send(JSON.stringify({
                            type: 'setUserType',
                            userType: userType
                        }));
                    }
                };

                ws.onmessage = (event) => {
                    try {
                        const data: WebSocketMessage = JSON.parse(event.data);
                        console.log('收到消息:', data);

                        switch (data.type) {
                            case 'register':
                                setUserId(data.userId || null);
                                if (!userId) {
                                    setUserType(data.userType as 'customer' | 'service' || 'customer');
                                }
                                break;

                            case 'history':
                                if (Array.isArray(data.messages)) {
                                    setMessages(data.messages);
                                } else {
                                    console.error('收到的历史消息不是数组:', data.messages);
                                }
                                break;

                            case 'message':
                                processNewMessage(data as Message);
                                break;

                            case 'historyCleaned':
                                // 处理服务器清除历史记录的通知
                                setMessages([
                                    {
                                        type: 'message',
                                        fromUserId: 'doctor',
                                        fromUserType: 'service',
                                        message: '您好！我是张医生，很高兴为您服务。\n请问有什么可以帮您?',
                                        timestamp: new Date().toISOString()
                                    }
                                ]);
                                console.log('聊天历史记录已被清除');
                                break;

                            case 'callRequest':
                                // 处理通话请求
                                Alert.alert(
                                    "通话请求",
                                    `收到来自 ${data.fromUserId} 的通话请求`,
                                    [
                                        { text: "拒绝", style: "cancel" },
                                        { text: "接受", onPress: () => handleAcceptCall(data.fromUserId || '') }
                                    ]
                                );
                                break;

                            default:
                                console.log('未知消息类型:', data);
                        }
                    } catch (error) {
                        console.error('处理消息错误:', error);
                    }
                };

                ws.onclose = (event) => {
                    console.log(`WebSocket连接已关闭，代码: ${event.code}, 原因: ${event.reason}`);
                    setConnected(false);
                    setConnecting(true);

                    // 使用number类型作为重连延迟
                    const reconnectDelay = 2000; // 2秒重连
                    reconnectTimeoutRef.current = setTimeout(() => {
                        console.log('尝试重新连接...');
                        connectWebSocket();
                    }, reconnectDelay);
                };

                ws.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    setConnected(false);
                    setConnecting(false);
                    setError('连接服务器失败，请检查服务器是否启动');
                };

                const heartbeatInterval = setInterval(() => {
                    if (ws.readyState === 1) {
                        ws.send(JSON.stringify({ type: 'pong' }));
                    }
                }, 15000); // 每15秒发送一次心跳

                return () => {
                    console.log('清理WebSocket连接...');
                    clearInterval(heartbeatInterval);
                    if (ws && ws.readyState <= 1) {
                        ws.close();
                    }
                };
            } catch (err) {
                console.error('连接WebSocket时出错:', err);
                setConnected(false);
                setConnecting(false);
                setError(`连接错误: ${err instanceof Error ? err.message : String(err)}`);

                // 5秒后重试
                reconnectTimeoutRef.current = setTimeout(connectWebSocket, 5000);
            }
        };

        connectWebSocket();

        return () => {
            if (reconnectTimeoutRef.current) {
                clearTimeout(reconnectTimeoutRef.current);
            }

            if (wsRef.current) {
                try {
                    wsRef.current.close();
                } catch (e) {
                    console.error('关闭WebSocket时出错:', e);
                }
            }
        };
    }, []);

    // 处理接受通话
    const handleAcceptCall = (userId: string) => {
        Alert.alert("通话已接通", `已与 ${userId} 建立通话连接`);
        // 这里实现实际的通话逻辑
    };

    // 发起通话请求
    const handleCallRequest = (type: 'audio' | 'video') => {
        if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
            wsRef.current.send(JSON.stringify({
                type: 'callRequest',
                callType: type,
                targetUserId: 'doctor' // 指定要通话的用户ID
            }));
            Alert.alert(`已发送${type === 'audio' ? '语音' : '视频'}通话请求`);
        } else {
            setError('WebSocket未连接，无法发起通话请求');
        }
    };

    // 切换用户类型
    const toggleUserType = () => {
        const newUserType = userType === 'customer' ? 'service' : 'customer';
        console.log(`切换用户类型: ${userType} -> ${newUserType}`);

        setUserType(newUserType);

        if (wsRef.current && wsRef.current.readyState === 1) {
            console.log('发送用户类型设置请求');
            wsRef.current.send(JSON.stringify({
                type: 'setUserType',
                userType: newUserType
            }));
        } else {
            console.warn('WebSocket未连接，无法发送用户类型设置请求');
        }

        setShowSettings(false);
    };

    // 发送消息
    const sendMessage = () => {
        if (!inputValue.trim() || !wsRef.current || wsRef.current.readyState !== 1) {
            console.warn('无法发送消息:', !inputValue.trim() ? '消息为空' : 'WebSocket未连接');
            return;
        }

        try {
            console.log(`发送消息: ${inputValue.trim()}, 用户类型: ${userType}`);

            const messageData = {
                type: 'message',
                message: inputValue.trim()
            };

            wsRef.current.send(JSON.stringify(messageData));

            const localMessage: Message = {
                type: 'message',
                fromUserId: userId || undefined,
                fromUserType: userType,
                message: inputValue.trim(),
                timestamp: new Date().toISOString(),
                isLocal: true
            };

            processNewMessage(localMessage);
            setInputValue('');
        } catch (err) {
            console.error('发送消息时出错:', err);
            setError(`发送失败: ${err instanceof Error ? err.message : String(err)}`);
        }
    };

    // 处理Enter键发送消息
    const handleKeyPress = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
        if (e.nativeEvent.key === 'Enter') {
            sendMessage();
        }
    };

    // 格式化时间显示
    const formatTime = (timeString: string): string => {
        if (!timeString) return new Date().toLocaleTimeString();

        try {
            const date = new Date(timeString);

            if (isNaN(date.getTime())) {
                return timeString;
            }

            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${hours}:${minutes}`;
        } catch (e) {
            console.error('格式化时间出错:', e);
            return timeString;
        }
    };

    // 处理新消息
    const processNewMessage = (newMessage: Message) => {
        setMessages(prevMessages => {
            // 检查是否已存在相同消息
            const isDuplicate = prevMessages.some(msg =>
                msg.timestamp === newMessage.timestamp &&
                msg.fromUserId === newMessage.fromUserId &&
                msg.message === newMessage.message
            );

            if (isDuplicate) {
                return prevMessages;
            }

            return [...prevMessages, newMessage];
        });
    };

    // 清除聊天记录
    const clearMessages = () => {
        if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
            console.warn('WebSocket未连接，无法清除聊天记录');
            setError('WebSocket未连接，无法清除聊天记录');
            setShowClearConfirm(false);
            return;
        }

        try {
            // 发送清除历史记录请求到服务器
            wsRef.current.send(JSON.stringify({
                type: 'clearHistory'
            }));
            
            // 本地先清除聊天记录
            setMessages([
                {
                    type: 'message',
                    fromUserId: 'doctor',
                    fromUserType: 'service',
                    message: '您好！我是张医生，很高兴为您服务。\n请问有什么可以帮您?',
                    timestamp: new Date().toISOString()
                }
            ]);
            
            console.log('已发送清除聊天记录请求');
            setShowClearConfirm(false);
        } catch (err) {
            console.error('发送清除历史记录请求时出错:', err);
            setError(`清除失败: ${err instanceof Error ? err.message : String(err)}`);
            setShowClearConfirm(false);
        }
    };

    return (
        <View style={styles.container}>
            <View style={styles.chatContainer}>
                {/* 顶部导航栏 */}
                <View style={styles.header}>
                    <TouchableOpacity
                        style={styles.backButton}
                        onPress={() => navigation.goBack()}
                    >
                        <Icon name="left" size={sp(20)} color="#333" />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>咨询</Text>
                    <View style={styles.headerRight}>
                        <TouchableOpacity 
                            style={styles.clearButton}
                            onPress={() => setShowClearConfirm(true)}
                        >
                            <Icon name="delete" size={sp(20)} color="#666" />
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.rightButton}>
                            <Text style={styles.notificationCount}>10</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                {/* 医生信息卡片 */}
                <View style={styles.doctorCard}>
                    <View style={styles.avatarContainer}>
                        <Text style={styles.avatarText}>Z</Text>
                    </View>
                    <View style={styles.doctorInfo}>
                        <Text style={styles.doctorName}>张医生</Text>
                        <Text style={styles.doctorTitle}>内科主治医师</Text>
                        <TouchableOpacity>
                            <Text style={styles.viewRating}>查看评价</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.callButtons}>
                        <TouchableOpacity 
                            style={styles.callButton}
                            onPress={() => handleCallRequest('audio')}
                        >
                            <Icon name="phone" size={sp(20)} color="#007AFF" />
                        </TouchableOpacity>
                        <TouchableOpacity 
                            style={styles.callButton}
                            onPress={() => handleCallRequest('video')}
                        >
                            <Icon name="videocamera" size={sp(20)} color="#007AFF" />
                        </TouchableOpacity>
                    </View>
                </View>

                {/* 聊天区域 */}
                <ScrollView 
                    style={styles.chatArea} 
                    ref={chatAreaRef}
                    contentContainerStyle={styles.chatContent}
                >
                    {/* 健康咨询说明 - 现在放在ScrollView内部 */}
                    <View style={styles.consultInfo}>
                        <Text style={styles.consultTitle}>健康咨询</Text>
                        <Text style={styles.consultDesc}>与专业医生在线交流，获得专业建议</Text>
                    </View>

                    {/* 快捷问题区域 - 现在放在ScrollView内部 */}
                    <View style={styles.quickQuestionsArea}>
                        <TouchableOpacity 
                            style={styles.quickQuestion}
                            onPress={() => setInputValue('感冒发烧怎么办?')}
                        >
                            <Text style={styles.quickQuestionText}>感冒发烧怎么办?</Text>
                        </TouchableOpacity>
                        <TouchableOpacity 
                            style={styles.quickQuestion}
                            onPress={() => setInputValue('高血压饮食建议')}
                        >
                            <Text style={styles.quickQuestionText}>高血压饮食建议</Text>
                        </TouchableOpacity>
                        <TouchableOpacity 
                            style={styles.quickQuestion}
                            onPress={() => setInputValue('糖尿病注意事项')}
                        >
                            <Text style={styles.quickQuestionText}>糖尿病注意事项</Text>
                        </TouchableOpacity>
                        <TouchableOpacity 
                            style={styles.quickQuestion}
                            onPress={() => setInputValue('失眠如何改善?')}
                        >
                            <Text style={styles.quickQuestionText}>失眠如何改善?</Text>
                        </TouchableOpacity>
                    </View>

                    {error && (
                        <View style={styles.errorNotice}>
                            <Text style={styles.errorMessage}>{error}</Text>
                        </View>
                    )}

                    {connecting && (
                        <View style={styles.connectingMessage}>
                            <Icon name="loading1" size={sp(20)} color="#666" />
                            <Text style={styles.connectingText}>正在连接服务器...</Text>
                        </View>
                    )}

                    {messages.map((msg, index) => (
                        <View
                            key={index}
                            style={[
                                styles.messageWrapper,
                                msg.fromUserType === userType ? styles.myMessage : styles.otherMessage,
                                msg.isLocal && styles.localMessage
                            ]}
                        >
                            {msg.fromUserType !== userType && (
                                <View style={styles.messageSenderAvatar}>
                                    <Text style={styles.avatarText}>Z</Text>
                                </View>
                            )}
                            <View style={[
                                styles.messageBubble,
                                msg.fromUserType === userType ? styles.myBubble : styles.otherBubble
                            ]}>
                                <Text style={[
                                    styles.messageText,
                                    msg.fromUserType === userType ? styles.myMessageText : styles.otherMessageText
                                ]}>
                                    {msg.message}
                                </Text>
                            </View>
                        </View>
                    ))}
                    <View ref={messageEndRef} />
                </ScrollView>

                {/* 底部输入区域 */}
                <View style={styles.bottomArea}>
                    <View style={styles.askArea}>
                        <Text style={styles.askLabel}>问一问</Text>
                        <View style={styles.inputArea}>
                            <TextInput
                                style={[styles.messageInput, !connected && styles.disabledInput]}
                                value={inputValue}
                                onChangeText={setInputValue}
                                onKeyPress={handleKeyPress}
                                placeholder="您有什么症状？"
                                placeholderTextColor="#999"
                                editable={connected}
                            />
                            <TouchableOpacity
                                style={[styles.sendButton, (!connected || !inputValue.trim()) && styles.disabledButton]}
                                onPress={sendMessage}
                                disabled={!connected || !inputValue.trim()}
                            >
                                <Icon name="right" size={sp(20)} color="#fff" />
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>

                {/* 清除聊天记录确认 Modal */}
                <Modal
                    visible={showClearConfirm}
                    transparent={true}
                    animationType="fade"
                    onRequestClose={() => setShowClearConfirm(false)}
                >
                    <View style={styles.modalOverlay}>
                        <View style={styles.confirmPanel}>
                            <Text style={styles.confirmTitle}>清除聊天记录</Text>
                            <Text style={styles.confirmMessage}>确定要清除所有聊天记录吗？此操作不可恢复。</Text>
                            <View style={styles.confirmButtonsContainer}>
                                <TouchableOpacity 
                                    style={styles.cancelButtonWrapper}
                                    onPress={() => setShowClearConfirm(false)}
                                >
                                    <Text style={styles.cancelButtonText}>取消</Text>
                                </TouchableOpacity>
                                <View style={styles.buttonDivider} />
                                <TouchableOpacity 
                                    style={styles.clearButtonWrapper}
                                    onPress={clearMessages}
                                >
                                    <Text style={styles.clearButtonText}>清除</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </Modal>

                {/* 设置面板 Modal */}
                <Modal
                    visible={showSettings}
                    transparent={true}
                    animationType="fade"
                    onRequestClose={() => setShowSettings(false)}
                >
                    <View style={styles.settingsPanel}>
                        <View style={styles.settingsHeader}>
                            <Text style={styles.settingsTitle}>设置</Text>
                            <TouchableOpacity onPress={() => setShowSettings(false)}>
                                <Icon name="close" size={sp(20)} color="#666" />
                            </TouchableOpacity>
                        </View>
                        <View style={styles.settingsContent}>
                            <View style={styles.settingItem}>
                                <Text style={styles.settingLabel}>用户ID:</Text>
                                <Text style={styles.idValue}>{userId || '未分配'}</Text>
                            </View>
                            <TouchableOpacity
                                style={[styles.roleToggleButton, !connected && styles.disabledButton]}
                                onPress={toggleUserType}
                                disabled={!connected}
                            >
                                <Text style={styles.roleToggleText}>
                                    切换为{userType === 'customer' ? '客服' : '客户'}
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </Modal>
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F8F9FB',
    },
    chatContainer: {
        flex: 1,
        backgroundColor: '#FFF',
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: wp(16),
        paddingVertical: hp(10),
        backgroundColor: '#FFF',
        borderBottomWidth: 1,
        borderBottomColor: '#EFEFEF',
    },
    backButton: {
        padding: wp(4),
    },
    headerTitle: {
        fontSize: sp(17),
        fontWeight: 'bold',
        color: '#333',
    },
    headerRight: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    clearButton: {
        padding: wp(8),
        marginRight: wp(8),
    },
    rightButton: {
        position: 'relative',
    },
    notificationCount: {
        backgroundColor: '#007AFF',
        color: '#FFF',
        fontSize: sp(12),
        width: wp(20),
        height: wp(20),
        borderRadius: wp(10),
        textAlign: 'center',
        lineHeight: wp(20),
        overflow: 'hidden',
    },
    doctorCard: {
        flexDirection: 'row',
        padding: wp(16),
        backgroundColor: '#FFF',
        alignItems: 'center',
    },
    avatarContainer: {
        width: wp(40),
        height: wp(40),
        borderRadius: wp(20),
        backgroundColor: '#E0E0E0',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: wp(12),
    },
    avatarText: {
        fontSize: sp(18),
        fontWeight: 'bold',
        color: '#666',
    },
    doctorInfo: {
        flex: 1,
    },
    doctorName: {
        fontSize: sp(16),
        fontWeight: 'bold',
        color: '#333',
    },
    doctorTitle: {
        fontSize: sp(12),
        color: '#666',
        marginTop: hp(4),
    },
    viewRating: {
        fontSize: sp(12),
        color: '#007AFF',
        marginTop: hp(4),
    },
    callButtons: {
        flexDirection: 'row',
    },
    callButton: {
        marginLeft: wp(12),
        padding: wp(8),
    },
    consultInfo: {
        padding: wp(16),
        backgroundColor: '#FFF',
        borderRadius: wp(8),
        marginBottom: hp(16),
    },
    consultTitle: {
        fontSize: sp(15),
        fontWeight: 'bold',
        color: '#333',
        marginBottom: hp(6),
    },
    consultDesc: {
        fontSize: sp(13),
        color: '#666',
    },
    quickQuestionsArea: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        padding: wp(16),
        backgroundColor: '#FFF',
        borderRadius: wp(8),
        marginBottom: hp(16),
    },
    quickQuestion: {
        backgroundColor: '#F0F6FF',
        borderRadius: wp(18),
        paddingHorizontal: wp(12),
        paddingVertical: hp(8),
        marginRight: wp(8),
        marginBottom: hp(8),
        borderWidth: 1,
        borderColor: '#D6E4FF',
    },
    quickQuestionText: {
        fontSize: sp(13),
        color: '#3069E3',
    },
    chatArea: {
        flex: 1,
        backgroundColor: '#F8F9FB',
    },
    chatContent: {
        padding: wp(16),
        paddingBottom: hp(20),
    },
    errorNotice: {
        backgroundColor: '#fff2f0',
        borderWidth: 1,
        borderColor: '#ffccc7',
        borderRadius: wp(8),
        padding: wp(16),
        marginBottom: hp(20),
    },
    errorMessage: {
        color: '#f5222d',
        textAlign: 'center',
        fontSize: sp(14),
    },
    connectingMessage: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        padding: wp(20),
    },
    connectingText: {
        fontSize: sp(14),
        color: '#666',
        marginLeft: wp(8),
    },
    messageWrapper: {
        flexDirection: 'row',
        marginBottom: hp(16),
        alignItems: 'flex-start',
    },
    myMessage: {
        alignSelf: 'flex-end',
        flexDirection: 'row-reverse',
    },
    otherMessage: {
        alignSelf: 'flex-start',
    },
    localMessage: {
        opacity: 0.7,
    },
    messageSenderAvatar: {
        width: wp(36),
        height: wp(36),
        borderRadius: wp(18),
        backgroundColor: '#E0E0E0',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: wp(8),
    },
    messageBubble: {
        padding: wp(12),
        borderRadius: wp(12),
        maxWidth: '70%',
    },
    myBubble: {
        backgroundColor: '#007AFF',
        borderBottomRightRadius: wp(4),
    },
    otherBubble: {
        backgroundColor: '#FFF',
        borderBottomLeftRadius: wp(4),
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.1,
        shadowRadius: 2,
        elevation: 1,
    },
    messageText: {
        fontSize: sp(14),
        lineHeight: hp(20),
    },
    myMessageText: {
        color: '#FFF',
    },
    otherMessageText: {
        color: '#333',
    },
    bottomArea: {
        borderTopWidth: StyleSheet.hairlineWidth,
        borderTopColor: '#E0E0E0',
        backgroundColor: '#FFF',
    },
    askArea: {
        padding: wp(16),
    },
    askLabel: {
        fontSize: sp(12),
        color: '#666',
        marginBottom: hp(8),
    },
    inputArea: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    messageInput: {
        flex: 1,
        height: hp(40),
        backgroundColor: '#F5F5F7',
        borderRadius: wp(20),
        paddingHorizontal: wp(16),
        marginRight: wp(8),
        fontSize: sp(14),
        color: '#333',
    },
    disabledInput: {
        backgroundColor: '#f0f0f0',
        color: '#999',
    },
    sendButton: {
        width: wp(40),
        height: wp(40),
        borderRadius: wp(20),
        backgroundColor: '#007AFF',
        alignItems: 'center',
        justifyContent: 'center',
    },
    disabledButton: {
        backgroundColor: '#CCCCCC',
    },
    settingsPanel: {
        backgroundColor: '#fff',
        margin: wp(30),
        borderRadius: wp(8),
        padding: wp(20),
    },
    settingsHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingBottom: hp(20),
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    settingsTitle: {
        fontSize: sp(18),
        fontWeight: '500',
    },
    settingsContent: {
        paddingTop: hp(20),
    },
    settingItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: hp(20),
    },
    settingLabel: {
        fontSize: sp(16),
        color: '#333',
    },
    idValue: {
        fontSize: sp(16),
        color: '#666',
        maxWidth: wp(200),
    },
    roleToggleButton: {
        backgroundColor: '#007AFF',
        padding: wp(15),
        borderRadius: wp(8),
        alignItems: 'center',
        marginTop: hp(10),
    },
    roleToggleText: {
        color: '#fff',
        fontSize: sp(16),
        fontWeight: '500',
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    confirmPanel: {
        backgroundColor: '#fff',
        borderRadius: wp(10),
        width: wp(280),
        overflow: 'hidden',
    },
    confirmTitle: {
        fontSize: sp(17),
        fontWeight: 'bold',
        color: '#000',
        textAlign: 'center',
        marginTop: hp(20),
        marginBottom: hp(8),
    },
    confirmMessage: {
        fontSize: sp(14),
        color: '#666',
        textAlign: 'center',
        paddingHorizontal: wp(20),
        marginBottom: hp(20),
    },
    confirmButtonsContainer: {
        flexDirection: 'row',
        borderTopWidth: StyleSheet.hairlineWidth,
        borderTopColor: '#E0E0E0',
    },
    cancelButtonWrapper: {
        flex: 1,
        paddingVertical: hp(12),
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttonDivider: {
        width: StyleSheet.hairlineWidth,
        backgroundColor: '#E0E0E0',
    },
    clearButtonWrapper: {
        flex: 1,
        paddingVertical: hp(12),
        alignItems: 'center',
        justifyContent: 'center',
    },
    cancelButtonText: {
        color: '#333',
        fontSize: sp(16),
    },
    clearButtonText: {
        color: '#FF3B30',
        fontSize: sp(16),
        fontWeight: 'bold',
    },
});

export default Ke;